package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.entity.CommonEntity;
import com.ruoyi.common.core.page.ResultEntity;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


@Api(tags = "驾驶舱")
@RestController
@RequestMapping("/client/homepage")
public class HomepageController {
    @Autowired
    private IHomepageService homepageService;
    @Autowired
    private TDeviceV2MaintenanceRecordService deviceV2MaintenanceRecordService;
    @Autowired
    private TDeviceV2LineWarnRecordService deviceV2LineWarnRecordService;
    @Autowired
    private ITProdService prodService;
    @Autowired
    private ITDeviceHandleLogService itDeviceHandleLogService;
    @Autowired
    private TDeviceV2InputService deviceV2InputService;
    @Autowired
    private ITProdRecordService prodRecordService;
    @Autowired
    private IAiAlarmDataService aiAlarmDataService;
    @GetMapping("/totalTask")
    @ApiOperation(value = "获取已生产记录")
    public ResultEntity totalTask(){
        return ResultEntity.createSuccess(homepageService.totalTask());
    }

    @GetMapping("/getInventory")
    @ApiOperation(value = "库存信息")
    public ResultEntity getInventory(){
        return ResultEntity.createSuccess(homepageService.getInventory());
    }

    @GetMapping("/getTaskRecordByDay")
    @ApiOperation(value = "获取产量走势")
    public ResultEntity getTaskRecordByDay(){
        return ResultEntity.createSuccess(homepageService.getTaskRecordByDay());
    }

    @GetMapping("/getEnvironment")
    @ApiOperation(value = "环境信息")
    public ResultEntity getEnvironment(){
        Map<String,Object> map = new HashMap<>();
        Random rand = new Random();
        int pm25 = rand.nextInt(60 - 50 + 1) + 50;
        int pm10 = rand.nextInt(25 - 20 + 1) + 20;
        int wind = rand.nextInt(30 - 10 + 1) + 10;
        int humidity = rand.nextInt(80 - 40 + 1) + 40;
        map.put("PM2.5",pm25);
        map.put("PM10",pm10);
        map.put("wind",wind);
        map.put("humidity",humidity);
        return ResultEntity.createSuccess(map);
    }

    @GetMapping("/listDeviceV2MaintenanceRecords")
    @ApiOperation(value = "获取运维记录")
    public ResultEntity listDeviceV2MaintenanceRecords(
            @RequestParam(value = "", required = false, defaultValue = "") String line
    ){
        return ResultEntity.createSuccess(deviceV2MaintenanceRecordService
                .list(new LambdaQueryWrapper<TDeviceV2MaintenanceRecord>()
                        .eq(TDeviceV2MaintenanceRecord::getProjectId,1L).eq(TDeviceV2MaintenanceRecord::getLine,line)
                        .orderByDesc(CommonEntity::getCreateTime)));
    }

    @GetMapping("/getProdList")
    @ApiOperation(value = "产品控制台",response = TProd.class)
    public ResultEntity getProdList(@RequestParam(value = "prodType", required = false) String prodType){
        TProdRecordDTO params = new TProdRecordDTO();
        params.setProdType(prodType);
        params.setProjectId(1L);
        params.setCheckFlag(false);
        return ResultEntity.createSuccess(prodRecordService.getByBatchCode(params));
    }

    @GetMapping("/getWarnList")
    @ApiOperation(value = "报警记录",response = TDeviceV2LineWarnRecord.class)
    public ResultEntity getWarnList(@RequestParam(value = "line") String line){
        return ResultEntity.createSuccess(deviceV2LineWarnRecordService.list(new LambdaQueryWrapper<TDeviceV2LineWarnRecord>()
                .eq(TDeviceV2LineWarnRecord::getProjectId,1L)
                .eq(TDeviceV2LineWarnRecord::getLine,line)
                .eq(TDeviceV2LineWarnRecord::getWarnType,"abnormal_alarm")
                .orderByDesc(TDeviceV2LineWarnRecord::getWarnTime)));
    }

//    @GetMapping("/getProdRecord")
//    @ApiOperation(value = "获取产品记录",response = TDeviceV2LineWarnRecord.class)
//    public ResultEntity getProdRecord(@RequestParam(value = "line") String line){
//
//    }


    @GetMapping("/suddenStop")
    @ApiOperation(value = "设备急停")
    public ResultEntity controlLine(@RequestParam(value = "prodType", required = false) String prodType){
        //产线信息  获取网关码
        TDeviceV2Input deviceV2Input = deviceV2InputService.getOne(new LambdaQueryWrapper<TDeviceV2Input>()
                .eq(TDeviceV2Input::getDeviceType,prodType));
        //组装报文
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        if(prodType.equals("xdg")){
            data.put("jt",true);
        } else if (prodType.equals("wp")) {
            data.put("qdtz",false);
        }else if (prodType.equals("ggj")) {
            data.put("zctz",true);
        }
        if(prodType.equals("ggj")){
            result.put("deviceId","ggjqg");
            result.put("serverId","ggjhj");
        }else {
            result.put("deviceId",prodType);
            result.put("serverId",prodType);
        }
        result.put("gatewayMac",deviceV2Input.getDeviceNum());
        result.put("time", System.currentTimeMillis());
        result.put("code",0);
        result.put("data",data);
        TDeviceHandleLog log = new TDeviceHandleLog();
        log.setDeviceNum(deviceV2Input.getDeviceNum());
        log.setProdId(null);
        log.setMessage(result.toJSONString());
        log.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        itDeviceHandleLogService.save(log);
        if(prodType.equals("xdg")){
            //小导管开关需复位
            xdgReset(deviceV2Input.getDeviceNum());
        } else if (prodType.equals("ggj")) {
            //钢拱架同时停止2台设备,再将焊接机也停止掉
            data.put("zctz1",true);
            result.put("data",data);
            result.put("deviceId","ggjhj");
            log.setMessage(result.toJSONString());
            itDeviceHandleLogService.save(log);
            ggjReset(deviceV2Input.getDeviceNum());
        }
        return ResultEntity.createSuccess();
    }

    @PostMapping("/device/sendData")
    @ApiOperation(value = "设备数据下发")
    public ResultEntity sendData(@RequestBody DeviceControlDTO deviceControlDto){
        //产品信息
        TProd prod = prodService.getById(deviceControlDto.getProdId());
        //产线信息  获取网关码
        TDeviceV2Input deviceV2Input = deviceV2InputService.getOne(new LambdaQueryWrapper<TDeviceV2Input>()
                .eq(TDeviceV2Input::getDeviceType,prod.getProdType()));
        //组装报文
        JSONObject result = new JSONObject();
        if(prod.getProdType().equals("xdg")){
            XdgMessage xdg = new XdgMessage();
            BeanUtils.copyProperties(prod,xdg);
            result.put("data",JSONObject.parseObject(JSONObject.toJSONString(xdg)));
        }else if(prod.getProdType().equals("wp")){
            WpMessage wp = new WpMessage();
            BeanUtils.copyProperties(prod,wp);
            result.put("data",JSONObject.parseObject(JSONObject.toJSONString(wp)));
        }else if(prod.getProdType().equals("ggj")){

            GgjMessage ggj = new GgjMessage();
            BeanUtils.copyProperties(prod,ggj);
            if(deviceControlDto.getGgjDeviceType().equals("qgjqg")){
                ggj.setXfsj(true);
                //钢拱架的下发把产品参数更新下
                prod.setClhd(deviceControlDto.getClhd());
                prod.setBj(deviceControlDto.getBj());
                prod.setWhc(deviceControlDto.getWhc());
                prod.setSdcl(deviceControlDto.getSdcl());
                prod.setPf(deviceControlDto.getPf());
                prodService.updateById(prod);
            }else {
                ggj.setXfsj1(true);
                prod.setWxc(deviceControlDto.getWxc());
                prod.setSdcl1(deviceControlDto.getSdcl1());
                prod.setPf1(deviceControlDto.getPf1());
                prodService.updateById(prod);
            }
            result.put("data",JSONObject.parseObject(JSONObject.toJSONString(ggj)));
        }
        if(prod.getProdType().equals("ggj")){
            result.put("deviceId",deviceControlDto.getGgjDeviceType());
            result.put("serverId","ggjhj");
        }else {
            result.put("deviceId",prod.getProdType());
            result.put("serverId",prod.getProdType());
        }
        result.put("gatewayMac",deviceV2Input.getDeviceNum());
        result.put("time", System.currentTimeMillis());
        result.put("code",0);
        TDeviceHandleLog log = new TDeviceHandleLog();
        log.setDeviceNum(deviceV2Input.getDeviceNum());
        log.setProdId(deviceControlDto.getProdId());
        log.setMessage(result.toJSONString());
        log.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        itDeviceHandleLogService.save(log);
        if(prod.getProdType().equals("ggj")){
            ggjReset(deviceV2Input.getDeviceNum());
        }
        return ResultEntity.createSuccess();
    }

    @PostMapping("/device/start")
    @ApiOperation(value = "设备启动")
    public ResultEntity startDevice(@RequestBody DeviceControlDTO deviceControlDto){
        //产品信息
        TProd prod = prodService.getById(deviceControlDto.getProdId());
        //产线信息  获取网关码
        TDeviceV2Input deviceV2Input = deviceV2InputService.getOne(new LambdaQueryWrapper<TDeviceV2Input>()
                .eq(TDeviceV2Input::getDeviceType,prod.getProdType()));
        //组装报文
        JSONObject result = new JSONObject();
        if(prod.getProdType().equals("xdg")){
            JSONObject data = new JSONObject();
            data.put("qd",true);
            result.put("data",data);
        }else if(prod.getProdType().equals("wp")){
            JSONObject data = new JSONObject();
            data.put("qdtz",true);
            result.put("data",data);
        }else if(prod.getProdType().equals("ggj")){
            if(deviceControlDto.getGgjDeviceType().equals("qgjqg")){
                JSONObject data = new JSONObject();
                data.put("qd",true);
                result.put("data",data);
            }else {
                JSONObject data = new JSONObject();
                data.put("qd1",true);
                result.put("data",data);
            }
        }
        if(prod.getProdType().equals("ggj")){
            result.put("deviceId",deviceControlDto.getGgjDeviceType());
            result.put("serverId","ggjhj");
        }else {
            result.put("deviceId",prod.getProdType());
            result.put("serverId",prod.getProdType());
        }
        result.put("gatewayMac",deviceV2Input.getDeviceNum());
        result.put("time", System.currentTimeMillis());
        result.put("code",0);
        TDeviceHandleLog log = new TDeviceHandleLog();
        log.setDeviceNum(deviceV2Input.getDeviceNum());
        log.setProdId(deviceControlDto.getProdId());
        log.setMessage(result.toJSONString());
        log.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        itDeviceHandleLogService.save(log);
        if(prod.getProdType().equals("xdg")){
            //小导管开关需复位
            xdgReset(deviceV2Input.getDeviceNum());
        }else if(prod.getProdType().equals("ggj")){
            ggjReset(deviceV2Input.getDeviceNum());
        }
        return ResultEntity.createSuccess();
    }

    @PostMapping("/device/stop")
    @ApiOperation(value = "设备停止")
    public ResultEntity stopDevice(@RequestBody DeviceControlDTO deviceControlDto){
        //产品信息
        TProd prod = prodService.getById(deviceControlDto.getProdId());
        //产线信息  获取网关码
        TDeviceV2Input deviceV2Input = deviceV2InputService.getOne(new LambdaQueryWrapper<TDeviceV2Input>()
                .eq(TDeviceV2Input::getDeviceType,prod.getProdType()));
        //组装报文
        JSONObject result = new JSONObject();
        if(prod.getProdType().equals("xdg")){
            JSONObject data = new JSONObject();
            data.put("zctj",true);
            result.put("data",data);
        }else if(prod.getProdType().equals("wp")){
            JSONObject data = new JSONObject();
            data.put("qdtz",false);
            result.put("data",data);
        }else if(prod.getProdType().equals("ggj")){
            if(deviceControlDto.getGgjDeviceType().equals("qgj")){
                JSONObject data = new JSONObject();
                data.put("zctz",true);
                result.put("data",data);
            }else {
                JSONObject data = new JSONObject();
                data.put("zctz1",true);
                result.put("data",data);
            }
        }
        result.put("deviceId",prod.getProdType());
        result.put("serverId",prod.getProdType());
        result.put("gatewayMac",deviceV2Input.getDeviceNum());
        result.put("time", System.currentTimeMillis());
        result.put("code",0);
        TDeviceHandleLog log = new TDeviceHandleLog();
        log.setDeviceNum(deviceV2Input.getDeviceNum());
        log.setProdId(deviceControlDto.getProdId());
        log.setMessage(result.toJSONString());
        log.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        itDeviceHandleLogService.save(log);
        if(prod.getProdType().equals("xdg")){
            //小导管开关需复位
            xdgReset(deviceV2Input.getDeviceNum());
        }else if(prod.getProdType().equals("ggj")){
            ggjReset(deviceV2Input.getDeviceNum());
        }
        return ResultEntity.createSuccess();
    }

    @PostMapping("/device/rset")
    @ApiOperation(value = "设备复位")
    public ResultEntity rset(@RequestBody Long prodId){
        //复位目前只有小导管有
        //产品信息
        TProd prod = prodService.getById(prodId);
        //产线信息  获取网关码
        TDeviceV2Input deviceV2Input = deviceV2InputService.getOne(new LambdaQueryWrapper<TDeviceV2Input>()
                .eq(TDeviceV2Input::getDeviceType,prod.getProdType()));
        //组装报文
        JSONObject result = new JSONObject();
        if(prod.getProdType().equals("xdg")){
            JSONObject data = new JSONObject();
            data.put("fw",true);
            result.put("data",data);
        }
        result.put("deviceId",prod.getProdType());
        result.put("serverId",prod.getProdType());
        result.put("gatewayMac",deviceV2Input.getDeviceNum());
        result.put("time", System.currentTimeMillis());
        result.put("code",0);
        TDeviceHandleLog log = new TDeviceHandleLog();
        log.setDeviceNum(deviceV2Input.getDeviceNum());
        log.setProdId(prodId);
        log.setMessage(result.toJSONString());
        log.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        itDeviceHandleLogService.save(log);
        if(prod.getProdType().equals("xdg")){
            //小导管开关需复位
            xdgReset(deviceV2Input.getDeviceNum());
        }
        return ResultEntity.createSuccess();
    }

    /**
     * 小导管控制执行完后复位
     * @param deviceNum
     */
    private void xdgReset(String deviceNum){
        //小导管的每个控制设备动作，true完之后需要给置为false重新下发，延迟3秒重新调用一次下发逻辑
        //避免麻烦，直接将所有动作置为false
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            System.out.println("线程暂停失败");
        }
        TDeviceHandleLog resetLog = new TDeviceHandleLog();
        resetLog.setDeviceNum(deviceNum);
        resetLog.setProdId(null);
        resetLog.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        JSONObject resetResult = new JSONObject();
        resetResult.put("deviceId","xdg");
        resetResult.put("serverId","xdg");
        resetResult.put("gatewayMac",deviceNum);
        resetResult.put("time", System.currentTimeMillis());
        resetResult.put("code",0);
        JSONObject resetData = new JSONObject();
        resetData.put("fw",false);
        resetData.put("jt",false);
        resetData.put("qd",false);
        resetData.put("zctj",false);
        resetResult.put("data",resetData);
        resetLog.setMessage(resetResult.toJSONString());
        itDeviceHandleLogService.save(resetLog);
    }

    /**
     * 钢拱架控制执行完后复位
     * @param deviceNum
     */
    private void ggjReset(String deviceNum){
        //小导管的每个控制设备动作，true完之后需要给置为false重新下发，延迟3秒重新调用一次下发逻辑
        //避免麻烦，直接将所有动作置为false
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            System.out.println("线程暂停失败");
        }
        //切割机复位
        TDeviceHandleLog resetLog = new TDeviceHandleLog();
        resetLog.setDeviceNum(deviceNum);
        resetLog.setProdId(null);
        resetLog.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        JSONObject resetResult = new JSONObject();
        resetResult.put("deviceId","ggjqg");
        resetResult.put("serverId","ggjhj");
        resetResult.put("gatewayMac",deviceNum);
        resetResult.put("time", System.currentTimeMillis());
        resetResult.put("code",0);
        JSONObject resetData = new JSONObject();
        resetData.put("qd",false);
        resetData.put("zctz",false);
        resetData.put("xfsj",false);
        resetResult.put("data",resetData);
        resetLog.setMessage(resetResult.toJSONString());
        itDeviceHandleLogService.save(resetLog);

        //焊接机复位
        TDeviceHandleLog resetLog2 = new TDeviceHandleLog();
        resetLog2.setDeviceNum(deviceNum);
        resetLog2.setProdId(null);
        resetLog2.setCreateBy(SecurityUtils.getLoginUser().getUser().getId());
        JSONObject resetResult2 = new JSONObject();
        resetResult2.put("deviceId","ggjhj");
        resetResult2.put("serverId","ggjhj");
        resetResult2.put("gatewayMac",deviceNum);
        resetResult2.put("time", System.currentTimeMillis());
        resetResult2.put("code",0);
        JSONObject resetData2 = new JSONObject();
        resetData2.put("qd1",false);
        resetData2.put("zctz1",false);
        resetData2.put("xfsj1",false);
        resetResult2.put("data",resetData2);
        resetLog2.setMessage(resetResult2.toJSONString());
        itDeviceHandleLogService.save(resetLog2);
    }

    @GetMapping("/totalWarnByAI")
    @ApiOperation(value = "AI摄像头数据预警统计")
    public ResultEntity totalWarnByAI(){
        List<Map<String, Object>> list = aiAlarmDataService.totalByAlgo();
        //拼接数据
        Map<String,Object> result = new HashMap<>();
        result.put("未带安全帽",0);
        result.put("反光背心",0);
        result.put("烟火监测",0);
        result.put("抽烟",0);
        list.forEach(item -> {
            if(String.valueOf(item.get("algoId")).contains("安全帽")){
                result.put("未带安全帽",item.get("num"));
            }
            if(String.valueOf(item.get("algoId")).contains("工作服")){
                result.put("反光背心",item.get("num"));
            }
            if(String.valueOf(item.get("algoId")).contains("烟火监测")){
                result.put("烟火监测",item.get("num"));
            }
            if(String.valueOf(item.get("algoId")).contains("抽烟")){
                result.put("抽烟",item.get("num"));
            }
        });
        return ResultEntity.createSuccess(result);
    }

    @GetMapping("/listLastWarnByAI")
    @ApiOperation(value = "AI摄像头数据预警列表")
    public ResultEntity listLastWarnByAI(){
        return ResultEntity.createSuccess(aiAlarmDataService.listLastWarnByAI());
    }

}
